package com.fast.develop.management.resource.compoment;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.fast.develop.core.io.ResourceManager;
import com.fast.develop.management.resource.utils.SchemaFileUtil;

import java.util.stream.Collectors;

/**
 * @author 莫寅
 * @createTime 2022-06-17 14:47
 * @desc：
 */
public class SchemaReader {

    private ResourceManager resourceManager;

    public SchemaReader(ResourceManager resourceManager) {
        this.resourceManager = resourceManager;
    }

    public String read(String path){

        String filePath = null;
        if(SchemaFileUtil.isSchemaNodePath(path)){
            filePath = SchemaFileUtil.getFilePath(path);
        }else{
            filePath = path;
        }

        byte[] bytes = resourceManager.read(filePath);
        String value = StrUtil.utf8Str(bytes);


        if(SchemaFileUtil.isSchemaNodePath(path)){
            String schemaType = SchemaFileUtil.getSchemaType(path);
            String nodeName = SchemaFileUtil.getSchemaNodeName(path);
            JSONObject jsonObject = JSONUtil.parseObj(value);
            JSONArray jsonArray = jsonObject.getJSONArray(schemaType);

            if(jsonArray != null){
                Object fieldObject = jsonArray.stream().filter(o -> ((JSONObject)o).getStr("name").equals(nodeName)).collect(Collectors.toList()).get(0);
                return fieldObject.toString();
            }

        }else{
            return value;
        }

        return null;
    }
}
